<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<!DOCTYPE html>
<html lang="zh-cmn-Hans">

<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<head>
    <base href="/">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0,user-scalable=no, shrink-to-fit=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="apple-mobile-web-app-capable" content="no"/>
    <meta name="format-detection" content="telephone=no">
    <title>确认信息</title>
    <script src="static/js/cssrem.js"></script>
    <link href="static/css/style.css" rel="stylesheet">
    <style>
    	.vh{visibility: hidden;left:-99999px;top:-99999px;}
    	.vv{visibility: visible;left:0;top:0;}
    </style>

<body>
<script>
document.domain='${topDomain}'
if (
  typeof test !== 'undefined' ||
  (typeof window.webkit !== 'undefined' && typeof window.webkit.messageHandlers.canJsGoBack !==
      'undefined')
) {
  document.write(
    '<header class="header"><div class="header-bg"></div><div class="titlet-bar white"><a class="btn-goback active dib" click="onGoBack"></a><div class="title ell g3">确认信息</div></div></header>'
  )
}else{
  document.write(
    '<header class="header dn"><div class="header-bg"></div><div class="titlet-bar white"><a class="btn-goback active dib" click="onGoBack"></a><div class="title ell g3">确认信息</div></div></header>'
  )
}
</script>
<!-- <header class="header">
    <div class="header-bg"></div>
    <div class="titlet-bar white">
        <a class="btn-goback active dib" click="onGoBack"></a>
        <div class="title ell g3">确认信息</div>
    </div>
</header> -->
<div class="content">
    <div class="wrapper">
        <!-- 物流信息 -->
 
        <div class="logistic cell bgwh <c:if test="${address == null }">null</c:if>">
            <div class="cell-hd">
                <i class="icon-location dib"></i>
            </div>
            <div class="cell-bd pl20 pr20">
                <c:choose>
                    <c:when test="${address == null }">
                        <div class="logistic__default">
                            <p class="f26">为了更好的为您提供邮寄到家服务，请</p>
                            <p class="f28 gf9953c">添加收货地址></p>
                        </div>
                    </c:when>
                    <c:otherwise>
                        <div class="logistic__default">
                            <p class="f28">
                                <span class="logistic__name">${address.name }</span>
                                <span class="logistic__phone pl20">${address.phone }</span>
                            </p>
                            <p class="f26 g6 logistic__address">收货地址：
                                <span>${address.provinceName }${address.cityName }${address.countryName }${address.townName }${address.address }
                                </span>
                            </p>
                        </div>
                    </c:otherwise>
                </c:choose>


            </div>
            <div class="cell-fd ion-ios-arrow-right"></div>
        </div>
        <!-- 商品信息 -->
        <div class="get-goods-info cell bgwh mt20">
            <div class="goods-photo cell-hd">
                <img src="${goodsSpecTime.thumb }" alt="">
            </div>
            <div class="goods-info cell-bd pl20">
                <p class="f0">
                    <span class="goods__period dib vm f28">${goodsSpecTime.timeDesc }</span>
                    <span class="goods__name dib vm f28">${goodsSpecTime.title }</span>
                </p>
                <div class="cell pt10">
                    <div class="cell-bd f30 gf9953c">¥${goodsSpecTime.price }</div>
                    <div class="cell-fd f26">×${goodsSpecTime.num }</div>
                </div>
            </div>
        </div>
        <!-- 认养信息 -->
        <div class="subscription">
            <h6 class="f30 pl20 n">认养信息</h6>
            <div class="cells bgwh f28">
                <div class="cell">
                    <div class="cell-hd pl0 g9">认养人：</div>
                    <div class="cell-bd tr">${userReal.realName}</div>
                </div>
                <div class="cell">
                    <div class="cell-hd pl0 g9">权益截止日：</div>
                    <div class="cell-bd tr">
                        ${fn:substring(goodsSpecTime.endUseTime, 0, 10)}
                    </div>
                </div>
            </div>
            <div class="cells mt20 bgwh f28">
                <div class="cell">
                    <div class="cell-hd pl0 g9">认养费用：</div>
                    <div class="cell-bd tr gf9953c">¥${totalPrice}</div>
                </div>
                <div class="cell">
                    <div class="cell-hd pl0 g9">运费：</div>
                    <div class="cell-bd tr gf9953c">¥0.00</div>
                </div>
                <div class="tips tr f26 gf9953c">现在下单提供免费邮寄服务</div>
            </div>
        </div>
    </div>
</div>

<div class="column-buy">
    <div class="cell">
        <div class="cell-hd"></div>
        <div class="cell-bd tl">
            <div class="f0 money pr20"><em class="dib vm f26 g6">实付款：</em><span class="dib vm f28">¥</span><em class="dib vm js-money b f34">${totalPrice}</em></div>
        </div>
        <div class="cell-fd">
            <form action="wap/pay/submitOrder" id="orderForm">
                <input type="hidden" name="goodsSpecTimeId" value="${goodsSpecTime.id }"/>
                <input type="hidden" name="goodsTimeId" value="${goodsSpecTime.goodsTimeId }"/>
                <input type="hidden" name="num" value="${goodsSpecTime.num }"/>
                <input type="hidden" name="totalPrice" value="${totalPrice }"/>
                <input type="hidden" name="submitToken" value="${submitToken }"/>
                <c:choose>
                    <c:when test="${address == null }">
                        <input type="hidden" name="addressId" id="addressId" value="-1"/>
                    </c:when>
                    <c:otherwise>
                        <input type="hidden" name="addressId" id="addressId" value="${address.id }"/>
                    </c:otherwise>
                </c:choose>
            </form>
            <input type="hidden" id="baseId" name="baseId" value="${goodsSpecTime.baseId }"/>
            <a class="btn-buy btn-buy--success f34 white js-buy" href="javascript:void(0)">提交订单</a>
        </div>
    </div>
</div>
<div class="iframe-layer dn"></div>
<div class="iframe vh">
<iframe src="${h5Domain}/receivingAddress" frameborder="0"></iframe>
</div>
<style>
.iframe-layer{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#f9f9f9;z-index:2;}
.iframe{width:100%;height:100%;position:absolute;top: 0;left: 0;z-index:3;overflow: auto;-webkit-overflow-scrolling:touch;}
.iframe.vh{visibility: hidden;left:-99999px;top:-99999px;}
.iframe iframe{width:100%;height:100%;}
</style>
<link href="https://cdn.bootcss.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet">
<script src="//cdn.bootcss.com/babel-polyfill/6.23.0/polyfill.min.js"></script>
<script src="static/js/layer_mobile/layer.js"></script>
<script src="https://cdn.bootcss.com/axios/0.16.2/axios.min.js"></script>
<script>
var ScrollFix = function (elem) {
    var startY, startTopScroll;
    elem = elem || document.querySelector(elem);
    if (!elem) return;
    elem.addEventListener('touchstart', function (event) {
      startY = event.touches[0].pageY;
      startTopScroll = elem.scrollTop;
      if (startTopScroll <= 0) elem.scrollTop = "1"
      if (startTopScroll + elem.offsetHeight >= elem.scrollHeight) elem.scrollTop = elem.scrollHeight - elem.offsetHeight -
        1;
    }, false);
  };
function selectAdd(){
	var hisLength = history.length
	var eIframe = document.querySelector('.iframe');
	var eIframeLayer = document.querySelector('.iframe-layer')
	eIframe.classList.remove('vh');
	eIframeLayer.classList.remove('dn');
	jumpHref({
      hash: 'addressList',
      id: 1,
      title: '收货地址'
    });
	var doc = eIframe.querySelector('iframe').contentWindow.document
	setTimeout(function(){
	var doc = eIframe.querySelector('iframe').contentWindow.document
	  ScrollFix(doc.querySelector('.content'))
	  //var eUl = doc.querySelector('.address-list')
	  doc.querySelector('div').addEventListener('click', function(e) {
		  var target = e.target
		  var _this = parentEle(target)
		  if(!_this) return false;
	      var id = _this.dataset.id 
	      var name = _this.querySelector('.name').textContent
	      var phone = _this.querySelector('.phone').textContent
	      var address = _this.querySelector('.address-info-address').textContent
	      console.log(id, name, phone, address)
	      getAddressJson({
	    	  id:id,
	    	  name:name,
	    	  phone:phone,
	    	  address:address
	      },1);
	      if(hisLength<history.length){
	    	  history.back()
	      }else{
	    	  eIframe.classList.add('vh')
	    	  eIframeLayer.classList.add('dn');
	    	  initLocalUrl()
	      }	      
	  })
	},1000)
}

window.addEventListener('popstate', onPopstate)

initLocalUrl()

function initLocalUrl(){
	if (typeof test !== 'undefined') {} else if (typeof window.webkit !== 'undefined'&&typeof window.webkit.messageHandlers.canJsGoBack !== 'undefined') {
    } else {
    	if (location.hash.indexOf('#') > -1) {
		    var len = location.hash.indexOf('#') > -1 ? location.href.indexOf('#') : location.href.length
		    var url = location.href.substring(0, len)
		    history.replaceState(null, '', url)
		}
    }
}

function jumpHref(obj) {
  var len = location.hash.indexOf('#') > -1 ? location.href.indexOf('#') : location.href.length
  var url = location.href.substring(0, len) + '#' + obj.hash
  history.pushState({
    address: obj.id,
    title: obj.title
  }, '', url)
  document.title = obj.title
}

function onPopstate() {
  var eIframe = document.querySelector('.iframe')
  var eIframeLayer = document.querySelector('.iframe-layer')
  var state = !!history.state && history.state.address ? history.state.address : 0
  if (!!state) {
    eIframe.classList.remove('vh')
    eIframeLayer.classList.remove('dn');
  } else {
    eIframe.classList.add('vh')
    eIframeLayer.classList.add('dn');
  }
}


function parentEle(ele) {
  if (ele.nodeName.toLowerCase()==='body') return false
  if (ele.classList.contains('address-listLi')) {
    return ele
  } else {
    return parentEle(ele.parentNode)
  }
}


	var isSubmit = true;
    $$('.js-buy').addEventListener('click', function (e) {
    	if(!isSubmit){
        	return;
        }
    	isSubmit = false;
        if ($$('.logistic').classList.contains('null') || $$('#addressId').value == '-1') {
        	isSubmit = true;
            layer.open({
                content: '请添加收货地址！'
                , skin: 'msg'
                , time: 2 //2秒后自动关闭
            });
            return false
        }
        submitForm();
    });
    function checkLogistics(id,callback){
    	var params = new FormData();
    	params.append('baseId',$$('#baseId').value);
    	params.append('addressId',id);
    	
    	axios({
            method: 'post',
            url: 'wap/order/mail/getLogisticsDoList',
            data: params,
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        }).then(function (res) {
            var data = res.data;
            var state = data.result.state;
            if (state == 1) {
            	callback()
            } else {
            	 //提示
            	  layer.open({
            	    content: '修改地址失败，新地址暂不支持配送~~'
            	    ,skin: 'msg'
            	    ,time: 2 //2秒后自动关闭
            	  });
            }

        }).catch(function (err) {
        	 //提示
      	  layer.open({
      	    content: '修改地址失败!'
      	    ,skin: 'msg'
      	    ,time: 2 //2秒后自动关闭
      	  });
        });
    }
    
    function submitForm() {
    	var formData = new FormData($$('#orderForm'))
        axios({
            method: 'post',
            url: 'wap/pay/submitOrderAsyn',
            data: formData,
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        }).then(function (res) {
        	isSubmit = true;
            var data = res.data;
            var state = data.result.state;
            if (state == 1) {
            	location.href = data.jump_url;
            } else {
            	var code = data.result.code;
            	if(code == 'loginOut'){
            		goLoginView();
            	}else{
            		if(data.jump_url != null){
            		layer.open({
            		    content: '<div><p>非常抱歉，</p><p>'+data.result.message+'</p></div>'
            		    ,btn: ['去实名', '取消']
            		    ,shadeClose:false
            		    ,yes: function(index){
            		      location.href = data.jump_url;
            		    }
            		  });
            		}else{
	            		layerShow('<div><p>非常抱歉，</p><p>'+data.result.message+'</p></div>',
	            				function() {
								setTimeout(function() {
									layer.closeAll()
								}, 2000)
						})
            		}
            	}
            }

        }).catch(function (err) {
        	isSubmit = true;
        });


	}
    
    $$('.logistic').addEventListener('click', function () {
        var id = $$('#addressId').value
        if (typeof test !== 'undefined') {
            test.jumpAddress(id)
        } else if (typeof window.webkit !== 'undefined'&&typeof window.webkit.messageHandlers.canJsGoBack !== 'undefined') {
            window.webkit.messageHandlers.jumpAddress.postMessage(id)
        } else {
        	selectAdd()
        }
    })

    function getAddressJson(addressJson,type) {
    	var html = '', id, address = ''
	        if (addressJson == 0) {
	            html = '<p class="f26">为了更好的为您提供邮寄到家服务，请</p><p class="f28 gf9953c">添加收货地址></p>'
	            $$('.logistic').classList.add('null')
	            $$('#addressId').value = '-1'
	            $$('.logistic__default').innerHTML = html
	        } else if (addressJson == 1) {
	            // 不操作
	
	        } else {
	            addressJson = typeof addressJson === 'string' ? JSON.parse(addressJson) : addressJson
	            id = addressJson.id
	            checkLogistics(id,function(){
		            address = (type===1)?addressJson.address:addressJson.provinceName + addressJson.cityName + addressJson.countryName + addressJson.address
		            html = '<p class="f28"><span class="logistic__name">' + addressJson.name + '</span><span class="logistic__phone pl20">' + addressJson.phone + '</span></p>' + '<p class="f26 g6 logistic__address">收货地址：<span>' + address + '</span></p>'
		            $$('.logistic').classList.remove('null')
		            $$('#addressId').value = id
		            $$('.logistic__default').innerHTML = html
	            })
	        }
    	

    }

    function $$(id) {
        return document.querySelector(id)
    }

    function layerShow(html, callback) {
		layer.open({
			shade : false,
			className : 'layer-tips',
			title : [ '', 'display:none' ],
			content : html,
			success : function(index) {
				(callback && typeof (callback) === "function")
						&& callback(index);
			}
		});
	}
    
	function goLoginView(){
		if (typeof test !== 'undefined') {
	          test.goLoginView()
	    } else if (typeof window.webkit !== 'undefined'&&typeof window.webkit.messageHandlers.canJsGoBack !== 'undefined') {
	      window.webkit.messageHandlers.goLoginView.postMessage('1111')
	    } else {
	    	location.href = '/wap/login/toLogin?forward='+encodeURIComponent('/wap/pay/firmOrder?goodsSpecTimeId=${goodsSpecTime.id}&goodsTimeId=${goodsSpecTime.goodsTimeId}&num=${goodsSpecTime.num}')+'&sourceChannel=0'
	    }
	}

</script>
<script type="text/javascript" src="static/js/app.js"></script>
	<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?24fb3d27099c50ae04b59301e492b50c";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>
</body>

</html>
